package com.fx.smsclient.modules.controller;

import com.fx.smsclient.modules.config.CmppParams;
import com.fx.smsclient.util.SendMsgUtil;
import com.fx.smsclient.util.response.SuccessResponseData;
import com.zx.sms.BaseMessage;
import com.zx.sms.LongSMSMessage;
import com.zx.sms.codec.cmpp.msg.CmppSubmitRequestMessage;
import com.zx.sms.codec.cmpp.msg.CmppSubmitResponseMessage;
import com.zx.sms.codec.cmpp.wap.LongMessageFrame;
import com.zx.sms.codec.cmpp.wap.LongMessageFrameHolder;
import lombok.extern.slf4j.Slf4j;
import org.marre.sms.SmsException;
import org.marre.sms.SmsMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;


@RestController
@Slf4j
public class SendMsgController {

    @Autowired
    CmppParams cmppParams;

    @PostMapping(value = "/sendMsg",produces= MediaType.APPLICATION_JSON_VALUE)
    Object sendMsg(@RequestBody HashMap paraMap) throws Exception {
        String phone = (String)paraMap.get("phone");
        String context =(String) paraMap.get("context");
        CmppSubmitRequestMessage msg = createMsg(phone, context);
        SendMsgUtil.putMsg(cmppParams.getUser(),msg);
        return SuccessResponseData.success(msg);
//        return SuccessResponseData.success(SendMsgUtil.sendMsg2(cmppParams.getUser(),msg));
    }

    @GetMapping("/hi")
    SuccessResponseData hi(){
        log.info("{}","hi");
        return SuccessResponseData.success("hi");
    }

    private CmppSubmitRequestMessage createMsg(String phone, String context) throws SmsException {
        CmppSubmitRequestMessage msg = new CmppSubmitRequestMessage();
        msg.setDestterminalId(phone);
        msg.setSrcId(cmppParams.getSrcId());
        msg.setLinkID("0000");
        msg.setMsgContent(context);
        msg.setRegisteredDelivery((short) 0);
        msg.setServiceId(cmppParams.getServiceId());
        SmsMessage msgcontent = ((LongSMSMessage)msg).getSmsMessage();
        List<LongMessageFrame> frameList = LongMessageFrameHolder.INS.splitmsgcontent(msgcontent);
        msg.setPktotal((short) frameList.size());
        return msg;
    }
}
